<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="880px">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="rules" label-width="130">
      <el-form-item label="线路名称" prop="routeName" class="pr-20px">
        <el-input v-model="formData.routeName" :maxlength="50" show-word-limit placeholder="如：XX煤矿-XX站台" />
      </el-form-item>
      <el-container class="!grid grid-cols-[6fr,4fr,1fr] gap-x-20px">
        <el-form-item label="装货地址" prop="loadingPlaceCode">
          <el-cascader ref="loadingCascaderRef" v-model="formData.loadingPlaceCode" :options="addressList" filterable
            clearable @change="loadingChange" @clear="loadingClear" class="!w-full">
          </el-cascader>
        </el-form-item>
        <el-form-item label-width="0">
          <el-input v-model="formData.loadingPlaceAddress" :maxlength="50" show-word-limit placeholder="请输入详细地址"
            class="!w-full" />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" plain @click="openMapDialog('loading')" class="!w-full">地图选点</el-button>
        </el-form-item>
      </el-container>
      <el-container class="!grid grid-cols-[6fr,4fr,1fr] gap-x-20px">
        <el-form-item label="卸货地址" prop="unloadingPlaceCode">
          <el-cascader ref="unloadingCascaderRef" v-model="formData.unloadingPlaceCode" :options="addressList"
            filterable clearable @change="unloadingChange" @clear="unloadingClear" class="!w-full">
          </el-cascader>
        </el-form-item>
        <el-form-item label-width="0">
          <el-input v-model="formData.unloadingPlaceAddress" :maxlength="50" show-word-limit placeholder="请输入详细地址"
            class="!w-full" />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" plain @click="openMapDialog('unloading')" class="!w-full">地图选点</el-button>
        </el-form-item>
      </el-container>
      <el-form-item label="备注" prop="remark" class="!w-full">
        <el-input type="textarea" v-model="formData.remark" :maxlength="100" show-word-limit placeholder="备注"
          class="!w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <MapPoints ref="mapPointsRef" :longitudelatitude="longitudelatitude" @success="success"></MapPoints>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import MapPoints from './mapPoints.vue'
  import * as AreaApi from '@/api/system/area'
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as lineManageApi from '@/api/transportation/lineManage'
  const emit = defineEmits(['success'])
  const mapPointsRef = ref()
  const formRef = ref()
  const { t } = useI18n()
  const dialogTitle = ref('')
  const message = useMessage()
  const dialogVisible = ref(false)
  const formLoading = ref(false)
  const addressList = ref([])
  const mapType = ref()
  const loadingCascaderRef = ref()
  const unloadingCascaderRef = ref()

  const formData = ref({
    id: undefined,
    routeName: undefined,
    loadingPlace: undefined,
    loadingPlaceCode: [],
    loadingPlaceLabel: [],
    loadingPlaceAddress: undefined,
    loadingPlaceCoordinates: [],
    unloadingPlace: undefined,
    unloadingPlaceCode: [],
    unloadingPlaceLabel: [],
    unloadingPlaceAddress: undefined,
    unloadingPlaceCoordinates: [],
    remark: undefined
  })

  const rules = reactive({
    routeName: [{ required: true, message: '请输入线路名称', trigger: 'blur' }],
    loadingPlaceCode: [{ required: true, message: '请选择装货地址', trigger: 'change' }],
    unloadingPlaceCode: [{ required: true, message: '请选择卸货地址', trigger: 'change' }]
  })

  const longitudelatitude = computed(() => {
    if (mapType.value === 'loading') {
      return { lat: formData.value.loadingPlaceCoordinates[0], lng: formData.value.loadingPlaceCoordinates[1] }
    }
    if (mapType.value === 'unloading') {
      return { lat: formData.value.unloadingPlaceCoordinates[0], lng: formData.value.unloadingPlaceCoordinates[1] }
    }
    return { lat: undefined, lng: undefined }
  })

  const open = async (id) => {
    resetFn()
    dialogVisible.value = true
    dialogTitle.value = id ? '编辑线路' : '添加线路'
    formData.value.id = id
    getAreaTree()
    if (formData.value.id) {
      getQeRoute()
    }
  }

  const getAreaTree = async () => {
    const result = await AreaApi.getAreaTree()
    addressList.value = handleResult(result)
  }

  const getQeRoute = async () => {
    const res = await lineManageApi.getQeRoute({ id: formData.value.id })
    Object.keys(formData.value).forEach((key) => {
      switch (key) {
        case 'loadingPlaceCode':
          formData.value.loadingPlaceCode = [res.loadingPlaceProvinceCode, res.loadingPlaceCityCode, res.loadingPlaceCountyCode, res.loadingPlaceTownCode]
          break;
        case 'loadingPlaceLabel':
          formData.value.loadingPlaceLabel = [res.loadingPlaceProvinceName, res.loadingPlaceCityName, res.loadingPlaceCountyName, res.loadingPlaceTownName]
          break;
        case 'loadingPlaceCoordinates':
          formData.value.loadingPlaceCoordinates = res.loadingPlaceCoordinates ? res.loadingPlaceCoordinates.split(',') : []
          break;
        case 'unloadingPlaceCode':
          formData.value.unloadingPlaceCode = [res.unloadingPlaceProvinceCode, res.unloadingPlaceCityCode, res.unloadingPlaceCountyCode, res.unloadingPlaceTownCode]
          break
        case 'unloadingPlaceLabel':
          formData.value.unloadingPlaceLabel = [res.unloadingPlaceProvinceName, res.unloadingPlaceCityName, res.unloadingPlaceCountyName, res.unloadingPlaceTownName]
          break
        case 'unloadingPlaceCoordinates':
          formData.value.unloadingPlaceCoordinates = res.unloadingPlaceCoordinates ? res.unloadingPlaceCoordinates.split(',') : []
          break
        default:
          formData.value[key] = res[key]
          break
      }
    })
  }

  const loadingChange = (value) => {
    formData.value.loadingPlaceCode = value
    formData.value.loadingPlaceLabel = loadingCascaderRef.value.getCheckedNodes()?.[0]?.pathLabels
  }

  const loadingClear = () => {
    formData.value.loadingPlaceCode = []
    formData.value.loadingPlaceLabel = []
  }

  const unloadingChange = (value) => {
    formData.value.unloadingPlaceCode = value
    formData.value.unloadingPlaceLabel = unloadingCascaderRef.value.getCheckedNodes()?.[0]?.pathLabels
  }

  const unloadingClear = () => {
    formData.value.unloadingPlaceCode = []
    formData.value.unloadingPlaceLabel = []
  }

  const handleResult = (result) => {
    result.forEach(e => {
      e.value = e.id
      e.label = e.name
      if (e.children?.length) {
        handleResult(e.children)
      }
    })
    return result
  }

  const openMapDialog = (type) => {
    mapType.value = type
    mapPointsRef.value.open()
  }

  const success = (latlng) => {
    if (mapType.value === 'loading') {
      formData.value.loadingPlaceCoordinates = [latlng.lat, latlng.lng]
    }
    if (mapType.value === 'unloading') {
      formData.value.unloadingPlaceCoordinates = [latlng.lat, latlng.lng]
    }
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    try {
      formLoading.value = true
      if (formData.value.id) {
        await lineManageApi.updateQeRoute(getBody())
      } else {
        await lineManageApi.createQeRoute(getBody())
      }
      message.success('操作成功')
      dialogVisible.value = false
      emit('success')
    } finally {
      formLoading.value = false
    }
  }

  const getBody = () => {
    const data = cloneDeep(formData.value)
    data['loadingPlaceProvinceCode'] = data.loadingPlaceCode[0]
    data['loadingPlaceCityCode'] = data.loadingPlaceCode[1]
    data['loadingPlaceCountyCode'] = data.loadingPlaceCode[2]
    data['loadingPlaceTownCode'] = data.loadingPlaceCode[3]
    data['loadingPlaceProvinceName'] = data.loadingPlaceLabel[0]
    data['loadingPlaceCityName'] = data.loadingPlaceLabel[1]
    data['loadingPlaceCountyName'] = data.loadingPlaceLabel[2]
    data['loadingPlaceTownName'] = data.loadingPlaceLabel[3]
    data.loadingPlace = `${data.loadingPlaceLabel.join('')}${data.loadingPlaceAddress || ''}`
    data['unloadingPlaceProvinceCode'] = data.unloadingPlaceCode[0]
    data['unloadingPlaceCityCode'] = data.unloadingPlaceCode[1]
    data['unloadingPlaceCountyCode'] = data.unloadingPlaceCode[2]
    data['unloadingPlaceTownCode'] = data.unloadingPlaceCode[3]
    data['unloadingPlaceProvinceName'] = data.unloadingPlaceLabel[0]
    data['unloadingPlaceCityName'] = data.unloadingPlaceLabel[1]
    data['unloadingPlaceCountyName'] = data.unloadingPlaceLabel[2]
    data['unloadingPlaceTownName'] = data.unloadingPlaceLabel[3]
    data.unloadingPlace = `${data.unloadingPlaceLabel.join('')}${data.unloadingPlaceAddress || ''}`
    data.loadingPlaceCoordinates = data.loadingPlaceCoordinates.join(',')
    data.unloadingPlaceCoordinates = data.unloadingPlaceCoordinates.join(',')
    delete data.loadingPlaceCode
    delete data.loadingPlaceLabel
    delete data.unloadingPlaceCode
    delete data.unloadingPlaceLabel
    if (!data.id) {
      delete data.id
    }
    return data
  }

  const resetFn = () => {
    Object.keys(formData.value).forEach(key => {
      if (['loadingPlaceCode', 'loadingPlaceLabel', 'loadingPlaceCoordinates', 'unloadingPlaceCode', 'unloadingPlaceLabel', 'unloadingPlaceCoordinates'].includes(key)) {
        formData.value[key] = []
      } else {
        formData.value[key] = undefined
      }
    })
    formRef.value?.resetFields()
  }

  defineExpose({ open })
</script>
<style lang="scss" scoped>
  :deep(.el-input__wrapper) {
    width: 100%;
  }

  :deep(.el-button--primary.is-plain) {
    background-color: #ffffff !important;
  }

  :deep(.el-button:focus),
  :deep(.el-button:hover) {
    color: var(--el-color-primary) !important;
  }
</style>